﻿using System;
using AccessControl.Wpf.ViewModels;
using AccessControl.Contracts.Models;
using AccessControl.Contracts.Managers;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace AccessControl.Wpf.Entries.ViewModels
{
	class EntriesViewModel : ViewModel, IActionViewModel
	{
		#region Fields

		private IEntry _SelectedEntry;
		private IEntriesManager _EntriesManager;
		private EntryViewModel _SelectedEntryViewModel;

		#endregion

		#region Public Constructor

		public EntriesViewModel(IEntriesManager entriesManager)
		{
			EntriesManager = entriesManager;
		}

		#endregion

		#region Public Properties

		public IEntriesManager EntriesManager
		{
			get { return _EntriesManager; }
			private set
			{
				if (_EntriesManager != value)
				{
					_EntriesManager = value;
					NotifyPropertyChanged("EntriesManager");
				}
			}
		}

		public IEntry SelectedEntry
		{
			get { return _SelectedEntry; }
			set
			{
				if (_SelectedEntry != value)
				{
					_SelectedEntry = value;
					NotifyPropertyChanged("SelectedEntry");
					if (_SelectedEntry != null)
						SelectedEntryViewModel = new EntryViewModel() { Entry = SelectedEntry };
					else
						SelectedEntryViewModel = null;
				}
			}
		}

		public EntryViewModel SelectedEntryViewModel
		{
			get { return _SelectedEntryViewModel; }
			set
			{
				if (_SelectedEntryViewModel != value)
				{
					/* Close the old one */
					if (_SelectedEntryViewModel != null)
						_SelectedEntryViewModel.Close();
					
					/* Set the new value */
					_SelectedEntryViewModel = value;
					NotifyPropertyChanged("SelectedEntryViewModel");

					/* Add the new cameras */
					foreach (ICamera camera in SelectedEntry.Cameras)
						_SelectedEntryViewModel.Cameras.Add(new CameraViewModel(camera));
					/* Start the new ones */
					if (_SelectedEntryViewModel != null)
					{
						foreach (CameraViewModel camera in _SelectedEntryViewModel.Cameras)
							camera.StartVideo();
					}
				}
			}
		}
		
		
		#endregion

		#region IActionViewModel Members

		public Contracts.Models.Action ViewModelAction
		{
			get { return Contracts.Models.Action.Operations; }
		}

		#endregion
	}
}
